import { useState, useMemo } from 'react'
import { View, Text } from '@tarojs/components'
import Taro, { showToast } from '@tarojs/taro'
import './paying.scss'

export default function Paying() {
  const [digits, setDigits] = useState<string>('')
  const password = '123456'
  const boxes = useMemo(() => {
    const arr = new Array(6).fill('') as string[]
    for (let i = 0; i < digits.length && i < 6; i++) {
      arr[i] = digits[i]
    }
    return arr
  }, [digits])

  const onPress = (key: string) => {
    if (/^\d$/.test(key)) {
      if (digits.length >= 6) return
      setDigits(prev => (prev + key).slice(0, 6))
    } else if (key === 'del') {
      if (!digits) return
      setDigits(prev => prev.slice(0, -1))
    } else if (key === 'clear') {
      setDigits('')
    } else if (key === 'ok') {
      if (digits.length !== 6) {
        showToast({ title: '请输入6位数字', icon: 'none' })
        return
      }
      
      if (digits !== password) {
        showToast({ title: '密码错误，请重新输入', icon: 'none' })
        setDigits('')
        return
      }
      
      showToast({ title: '支付中...', icon: 'loading', duration: 800 })
      setTimeout(() => {
        showToast({ title: '支付成功', icon: 'success' })
        Taro.navigateBack({})
      }, 800)
    }
  }

  const keys = [
    ['1', '2', '3'],
    ['4', '5', '6'],
    ['7', '8', '9'],
    ['clear', '0', 'del']
  ]

  return (
    <View className="paying-container">
      <Text className="title">输入支付密码</Text>

      <View className="code-boxes">
        {boxes.map((ch, idx) => (
          <View key={idx} className={`code-box ${digits.length === idx ? 'active' : ''}`}>
            <Text className="dot">{ch ? '●' : ''}</Text>
          </View>
        ))}
      </View>

      <View className="keyboard">
        {keys.map((row, rIdx) => (
          <View key={rIdx} className="kb-row">
            {row.map(k => (
              <View
                key={k}
                className={`kb-key ${k}`}
                onClick={() => onPress(k)}
              >
                <Text className="kb-text">
                  {k === 'del' ? '删除' : k === 'clear' ? '清空' : k}
                </Text>
              </View>
            ))}
          </View>
        ))}
        <View className="kb-row">
          <View className="kb-key ok" onClick={() => onPress('ok')}>
            <Text className="kb-text">完成</Text>
          </View>
        </View>
      </View>
    </View>
  )
}

